package com.apkicon.fallback;

import com.apkicon.model.IconInfo;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 使用Google Bundletool作为APK图标提取的fallback工具
 * 注意：需要单独下载bundletool.jar文件
 */
public class BundletoolIconExtractor {
    
    private static final String BUNDLETOOL_JAR = "bundletool.jar";
    private static final String TEMP_DIR_PREFIX = "apk-icon-extractor-";
    
    /**
     * 使用bundletool提取APK图标
     * @param apkFile APK文件
     * @param targetSize 目标尺寸
     * @return 图标信息，如果失败返回null
     */
    public IconInfo extractIconWithBundletool(File apkFile, int targetSize) {
        Path tempDir = null;
        try {
            // 创建临时目录
            tempDir = Files.createTempDirectory(TEMP_DIR_PREFIX);
            
            // 使用bundletool提取APK内容
            Path extractedDir = extractApkWithBundletool(apkFile, tempDir);
            if (extractedDir == null) {
                return null;
            }
            
            // 查找图标文件
            BufferedImage iconImage = findIconInExtractedFiles(extractedDir);
            if (iconImage == null) {
                return null;
            }
            
            // 调整尺寸
            BufferedImage resizedImage = resizeImage(iconImage, targetSize);
            
            return new IconInfo(resizedImage, IconInfo.IconType.PNG, "bundletool-extracted");
            
        } catch (Exception e) {
            System.err.println("Bundletool extraction failed: " + e.getMessage());
            return null;
        } finally {
            // 清理临时目录
            if (tempDir != null) {
                cleanupTempDirectory(tempDir);
            }
        }
    }
    
    /**
     * 使用bundletool提取APK内容
     */
    private Path extractApkWithBundletool(File apkFile, Path tempDir) {
        try {
            String bundletoolPath = getBundletoolPath();
            if (bundletoolPath == null) {
                System.err.println("Bundletool JAR not found. Please download bundletool.jar and place it in the current directory.");
                return null;
            }
            
            // 创建bundletool命令
            ProcessBuilder pb = new ProcessBuilder(
                "java", "-jar", bundletoolPath, 
                "extract-apks", 
                "--bundle=" + apkFile.getAbsolutePath(),
                "--output-dir=" + tempDir.toString()
            );
            
            pb.redirectErrorStream(true);
            Process process = pb.start();
            
            // 等待进程完成
            boolean finished = process.waitFor(30, TimeUnit.SECONDS);
            if (!finished) {
                process.destroyForcibly();
                return null;
            }
            
            if (process.exitValue() != 0) {
                return null;
            }
            
            return tempDir;
            
        } catch (Exception e) {
            System.err.println("Failed to run bundletool: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 在提取的文件中查找图标
     */
    private BufferedImage findIconInExtractedFiles(Path extractedDir) {
        try {
            // 查找APK文件
            List<Path> apkFiles = Files.walk(extractedDir)
                .filter(path -> path.toString().endsWith(".apk"))
                .collect(java.util.stream.Collectors.toList());
            
            for (Path apkFile : apkFiles) {
                BufferedImage icon = extractIconFromApk(apkFile);
                if (icon != null) {
                    return icon;
                }
            }
            
            return null;
            
        } catch (Exception e) {
            System.err.println("Failed to find icon in extracted files: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 从APK文件中提取图标
     */
    private BufferedImage extractIconFromApk(Path apkFile) {
        try (ZipFile zipFile = new ZipFile(apkFile.toFile())) {
            
            // 查找图标文件
            ZipEntry iconEntry = findIconEntry(zipFile);
            if (iconEntry == null) {
                return null;
            }
            
            // 读取图标
            try (InputStream is = zipFile.getInputStream(iconEntry)) {
                return ImageIO.read(is);
            }
            
        } catch (Exception e) {
            System.err.println("Failed to extract icon from APK: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 查找图标条目
     */
    private ZipEntry findIconEntry(ZipFile zipFile) {
        // 按优先级查找图标
        String[] iconPatterns = {
            "res/mipmap-xxxhdpi/ic_launcher.png",
            "res/mipmap-xxhdpi/ic_launcher.png", 
            "res/mipmap-xhdpi/ic_launcher.png",
            "res/mipmap-hdpi/ic_launcher.png",
            "res/mipmap-mdpi/ic_launcher.png",
            "res/drawable-xxxhdpi/ic_launcher.png",
            "res/drawable-xxhdpi/ic_launcher.png",
            "res/drawable-xhdpi/ic_launcher.png",
            "res/drawable-hdpi/ic_launcher.png",
            "res/drawable-mdpi/ic_launcher.png"
        };
        
        for (String pattern : iconPatterns) {
            ZipEntry entry = zipFile.getEntry(pattern);
            if (entry != null) {
                return entry;
            }
        }
        
        // 查找任何PNG文件
        return zipFile.stream()
            .filter(entry -> !entry.isDirectory() && entry.getName().endsWith(".png"))
            .filter(entry -> entry.getName().contains("ic_launcher") || entry.getName().contains("icon"))
            .findFirst()
            .orElse(null);
    }
    
    /**
     * 调整图像尺寸
     */
    private BufferedImage resizeImage(BufferedImage originalImage, int targetSize) {
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        
        if (originalWidth == targetSize && originalHeight == targetSize) {
            return originalImage;
        }
        
        BufferedImage resizedImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
        java.awt.Graphics2D g2d = resizedImage.createGraphics();
        
        try {
            // 设置高质量渲染
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, 
                java.awt.RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, 
                java.awt.RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, 
                java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
            
            // 计算缩放比例
            double scaleX = (double) targetSize / originalWidth;
            double scaleY = (double) targetSize / originalHeight;
            double scale = Math.min(scaleX, scaleY);
            
            int scaledWidth = (int) (originalWidth * scale);
            int scaledHeight = (int) (originalHeight * scale);
            int x = (targetSize - scaledWidth) / 2;
            int y = (targetSize - scaledHeight) / 2;
            
            g2d.drawImage(originalImage, x, y, scaledWidth, scaledHeight, null);
            
        } finally {
            g2d.dispose();
        }
        
        return resizedImage;
    }
    
    /**
     * 获取bundletool路径
     */
    private String getBundletoolPath() {
        // 尝试从当前目录查找
        File bundletoolFile = new File(BUNDLETOOL_JAR);
        if (bundletoolFile.exists()) {
            return bundletoolFile.getAbsolutePath();
        }
        
        // 尝试从系统PATH中查找
        try {
            ProcessBuilder pb = new ProcessBuilder("where", "bundletool.jar");
            Process process = pb.start();
            if (process.waitFor() == 0) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                    String path = reader.readLine();
                    if (path != null && new File(path).exists()) {
                        return path;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略错误
        }
        
        return null;
    }
    
    /**
     * 清理临时目录
     */
    private void cleanupTempDirectory(Path tempDir) {
        try {
            Files.walk(tempDir)
                .sorted(java.util.Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
        } catch (Exception e) {
            System.err.println("Failed to cleanup temp directory: " + e.getMessage());
        }
    }
    
    /**
     * 检查bundletool是否可用
     */
    public boolean isBundletoolAvailable() {
        String bundletoolPath = getBundletoolPath();
        if (bundletoolPath == null) {
            return false;
        }
        
        try {
            ProcessBuilder pb = new ProcessBuilder("java", "-jar", bundletoolPath, "--help");
            Process process = pb.start();
            boolean finished = process.waitFor(5, TimeUnit.SECONDS);
            if (finished && process.exitValue() == 0) {
                return true;
            }
        } catch (Exception e) {
            // bundletool不可用
        }
        return false;
    }
}
